//
//  EntryFirstpageViewController.swift
//  mggz
//
//  Created by 匀视网Mac on 2018/3/7.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import MobileCoreServices

class EntryFirstpageViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    @IBOutlet weak var idButton: UIButton!
    
    @IBOutlet weak var headerView: UIButton!
    
    @IBOutlet weak var informationView: UIView!
    
    @IBOutlet weak var nameLabel: UILabel!
    
    @IBOutlet weak var sexLabel: UILabel!
    
    @IBOutlet weak var ageLabel: UILabel!
    
    @IBOutlet weak var cardLabel: UILabel!
    
    @IBOutlet weak var adressLabel: UILabel!
    @IBOutlet weak var reCameraBtn: UIButton!
    @IBOutlet weak var editResultBtn: UIButton!
    @IBOutlet weak var headlayoutview: UIView!
    var inforationArray:NSMutableArray?
    
    var currentProject:LCProjectListModel?
    var userAge:String?
    
    var sfzhImg,headImg:UIImage?
    
    
    func reset(){
        self.headerView.setImage(UIImage(named: "scene_touxiang"), for: .normal)
        self.idButton.setImage(UIImage(named: "sfz"), for: .normal)
        self.setShowOrHide(false)
        
        self.sfzhImg = nil
        self.headImg = nil
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setShowOrHide(false)
        self.informationView.shadowEnable = true
        self.headlayoutview.shadowEnable = true
        self.navigationItem.title = "民工入职"
        
        
       AipOcrService.shard().auth(withAK: BaiduYunAPIKey, andSK: BaiduYunSecretKey)
      self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "下一步", fontSize: 17, self, #selector(nextPageClick))
    }
    
    override func viewDidLayoutSubviews() {
        self.headerView.imageView?.contentMode = .scaleAspectFill
        
        self.headerView.imageView?.layer.cornerRadius = (self.headerView.imageView?.bounds.width)! / 2
        self.headerView.imageView?.layer.masksToBounds = true
    }
    
    func setShowOrHide(_ flag:Bool){//true 显示 false 隐藏
            self.informationView.isHidden = !flag
            self.reCameraBtn.isHidden = !flag
            self.editResultBtn.isHidden = !flag
        self.reCameraBtn.isUserInteractionEnabled = flag
        self.editResultBtn.isUserInteractionEnabled = flag
        
    }
    @objc func nextPageClick(){
        if self.headImg == nil{
            QWTextonlyHud("请先上传头像", target: self.view)
            return
        }else if self.sfzhImg == nil{
            QWTextonlyHud("请先扫描身份证", target: self.view)
            return
        }
        var flag = true
        self.inforationArray?.forEach({ (item) in
            if item == nil || item as? String == ""{
                flag = false
            }
        })
        if !flag {
            QWTextonlyHud("扫描信息不完整，请重新扫描", target: self.view)
            return
        }
        QWTextWithStatusHud("正在加载...", target: self.view)
        var params:[String:Any] = ["lealPersonIDCard":self.userAge ?? ""]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .REGISTSFZH, params: &params, type: RegistWorker.self, success: { (bean,_) in
            QWHudDiss(self.view)
            guard let data = bean as? RegistWorker else{
                QWTextonlyHud("数据异常", target: self.view)
                return
            }
            
            guard let vc = UIStoryboard(name: "Contractor", bundle: nil).instantiateViewController(withIdentifier: "RegistWorkerController") as? RegistWorkerController else{
                return
            }
            vc.birthday = self.inforationArray![2] as! String
            vc.headimg = self.headImg
            vc.sfzimg = self.sfzhImg
            vc.information = self.inforationArray
            vc.currentProject = self.currentProject
            self.navigationController?.pushViewController(vc, animated: true)
        }) { (error) in
            QWTextonlyHud("数据异常", target: self.view)
        }
    }
    
    @IBAction func headerViewClick(_ sender: Any) {
        /*let tool = PhotoSheet()
        tool.showPhotoSheet(viewController: self) { (imgs) in
            if imgs != nil && imgs!.count > 0 {
                self.headImg = imgs?.first
                self.headerView.setImage(imgs?.first, for: .normal)
            }
        }*/
        //直接拍照
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self
        imagePickerController.sourceType = UIImagePickerControllerSourceType.camera
        imagePickerController.allowsEditing = true
        imagePickerController.showsCameraControls = true
        imagePickerController.cameraDevice = UIImagePickerControllerCameraDevice.rear
        imagePickerController.mediaTypes = [kUTTypeImage as String]
        
        self.present(imagePickerController, animated: true, completion: nil)
        
    }
    @IBAction func idButtonClick(_ sender: Any) {
        let ocrVc = AipCaptureCardVC.viewController(with: .localIdCardFont) { (ocrImage) in
            AipOcrService.shard().detectIdCardFront(from: ocrImage, withOptions: nil, successHandler: { (result) in
                
                DispatchQueue.main.async {
                    self.setShowOrHide(true)
                    self.setupResultWithUI(result as! [String : AnyObject])
                    self.dismiss(animated: true, completion: {
                        
                    })
                    self.sfzhImg = ocrImage
                    self.idButton.setImage(ocrImage, for: UIControlState.normal)
                    //self.idButton.setBackgroundImage(ocrImage, for: UIControlState.normal)
                }
            }, failHandler: { (error) in
                
            })
        }
        self.present(ocrVc!, animated: true) {
            
        }
        
    }
    fileprivate func setupResultWithUI(_ result:[String:AnyObject]){
         self.inforationArray = NSMutableArray.init()
        if (result["words_result"] != nil){
            (result["words_result"])?.enumerateKeysAndObjects({ (mykey, myObj, myStop) in
                guard let selectObj : NSDictionary = myObj as? NSDictionary else{
                     return
                }
                if let selectWord = selectObj["words"] {
                    self.inforationArray?.add(selectWord)
                }else{
                    return
                }
            })
        }else{
            
        }
        self.setResult()
        
        
    }
    
    func setResult(){
        self.nameLabel.text = self.inforationArray![0] as? String
        self.userAge = self.switchDateToAge(self.inforationArray![1] as! String)
        //if userAge == nil{}
        
        
        self.ageLabel.text = userAge
        //self.inforationArray?.replaceObject(at: 1, with: userAge)
        self.cardLabel.text = self.inforationArray?[2] as? String
        self.sexLabel.text = self.inforationArray?[3] as? String
        self.adressLabel.text = self.inforationArray?[4] as? String
    }
    fileprivate func switchDateToAge(_ year:String) -> String{
        let formate = DateFormatter()
        formate.dateFormat = "yyyyMMdd"
        var current = Calendar.current.dateComponents([.year,.month,.day], from: formate.date(from: year)!)
        var cur = Calendar.current.dateComponents([.year], from: Date())
        return "\((cur.year ?? 0) - (current.year ?? 0))"
    }
    
    func editResult(_ result:Any,_age age:String){
        self.userAge = age
        self.inforationArray?.removeAllObjects()
        self.inforationArray = NSMutableArray.init(array: (result as! NSArray))
        print("\(self.inforationArray)")
        self.setResult()
    }
    
    func text(_ str:Any){
        print("测试")
    }
    
    @IBAction func reScaningClick(_ sender: Any) {
        
        
        
        
        
    }
    @IBAction func reSetInfoClick(_ sender: Any) {
        
        let modifiView = PersonalInfoModViewController(nibName: "PersonalInfoModViewController", bundle: nil)
        modifiView.informationArray = self.inforationArray
        modifiView.idImage = self.sfzhImg
        self.navigationController?.pushViewController(modifiView, animated: true)
        
    }

    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        guard var photo = info[UIImagePickerControllerOriginalImage] as? UIImage else{
            return
        }
        self.headImg = photo
        self.headerView.setImage(photo, for: .normal)
        picker.dismiss(animated: true, completion: nil)
        
        /*if photo != nil {
         if let handler = self.choosePhotoHandler {
         handler([photo as! UIImage])
         }
         }*/
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true) {
            //self.removeFromParentViewController()
            //self.view.removeFromSuperview()
            picker.dismiss(animated: true, completion: nil)
        }
    }
}





